//
//  KeepBookViewController.swift
//  手账
//
//  Created by zhuxiaoxiang on 2018/12/16.
//  Copyright © 2018年 zhuxiaoxiang. All rights reserved.
//

import UIKit

class KeepBookViewController: BaseViewController {

    @IBOutlet weak var countTF: UITextField!
    @IBOutlet weak var channelTF: UITextField!
    
    fileprivate lazy var incomeArray = ["工资", "投资", "奖金", "兼职", "红包", "其他"]
    fileprivate lazy var expendArray = ["餐饮", "购物", "日用", "交通", "数码", "电影", "烟酒", "旅行", "住房", "服饰", "通讯", "宠物"]
    
    fileprivate lazy var segmentView: SegmentView = {
       let one = SegmentView(frame: CGRect(x: 0, y: 0, width: 160, height: 40))
        one._block = { (moneyType) in
            self.pickerView._data = moneyType == .income ? self.incomeArray : self.expendArray
        }
        return one
    }()
    
    fileprivate var pickerView: PickerView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        configBackItem()
    }
    
    override func config() {
        super.config()
        self.navigationItem.titleView = self.segmentView
    }
    
    override func configBackItem() {
        super.configBackItem()
    }
}

extension KeepBookViewController: UITextFieldDelegate {
    func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
        if textField == channelTF {
            self.pickerView = PickerView.init(frame: self.view.bounds, data: self.segmentView.moneyType == .income ? self.incomeArray : self.expendArray)
            self.pickerView._block = { (text) in
                self.channelTF.text = text
            }
            self.view.addSubview(self.pickerView)
            return false
        }
        return true
    }
    
    @IBAction func confirmBook(_ sender: UIButton) {
        let count = countTF.text
        let channel = channelTF.text
        if count?.count == 0 {
            self.showMessage("请输入金额")
            return
        }
        if channel?.count == 0 {
            self.showMessage("请选择途径")
            return
        }
        let object = BmobObject.init(className: "Book")
        object?.setObject(count, forKey: "count")
        object?.setObject(channel, forKey: "channel")
        object?.setObject(self.segmentView.moneyType == .income ? "income" : "expend", forKey: "moneytype")
        object?.setObject(AppUser.sharedInstance.phone, forKey: "author")
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd"
        let dateStr = dateFormatter.string(from: Date())
        object?.setObject(dateStr, forKey: "date")
        object?.saveInBackground(resultBlock: { (isSuc, error) in
            if isSuc == true {
                self.showMessage("记账成功")
                sleep(2)
                self.navigationController?.popViewController(animated: true)
            }else {
                self.showMessage("记账失败")
            }
        })
    }
}
